package com.simple.mybaits.simplemybatis.proxy;

import com.simple.mybaits.simplemybatis.Configuration;
import com.simple.mybaits.simplemybatis.comandEnum.SqlCommand;
import com.simple.mybaits.simplemybatis.session.SqlSession;
import com.simple.mybaits.simplemybatis.statement.MapperStatement;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author :  zxj
 * @package :  com.simple.mybaits.simplemybatis
 * @date :  2018/5/21
 * @description :
 */
public class MapperProxy implements InvocationHandler {

    private SqlSession sqlSession;
    private Class<?> mapperInterface;
    private  Configuration configuraion;

    @Override
    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
        String mapperId = mapperInterface.getName() +"."+ method.getName();
        MapperStatement ms =  configuraion.getMapperStatementRegister().get(mapperId);
        if(ms  == null){
            throw  new RuntimeException("MapperStatement not found");
        }
        if(SqlCommand.SELECT.equals(ms.getSqlCommand())){
           return sqlSession.selectList(ms,objects);
        }if(SqlCommand.INSERT.equals(ms.getSqlCommand())){

        }if(SqlCommand.UPDATE.equals(ms.getSqlCommand())){

        }if(SqlCommand.DELETE.equals(ms.getSqlCommand())){

        }

        return null;
    }

    public <T> T newInstance(Class<?> target) {
        this.mapperInterface = target;
        return (T) Proxy.newProxyInstance(target.getClassLoader(),new Class<?>[]{target}, this);
    }

    public void setSqlSession(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    public void setConfiguraion(Configuration configuraion) {
        this.configuraion = configuraion;
    }
}
